import axios from "axios";

// 服务端地址
const baseURL = "./";

// 创建请求客户端
const api = axios.create({ baseURL, validateStatus: status => status <= 404 });
const responseInterceptor = response => {
    if (response.data instanceof Blob) {
        return Promise.resolve(response);
    }

    // 未授权，发起授权
    if (response.status === 401 || response.data.status === 401) {
        // token失效
        return
    }
    if (response.status !== 200 || (response.data.status && response.data.status !== 200)) {
        return Promise.reject(response.data.msg);
    }
    return Promise.resolve(
        response.data
    );
};

// 配置响应解析拦截器
api.interceptors.response.use(responseInterceptor);
api.interceptors.request.use(
    config => {
        if (config.headers === undefined || config.headers === null) {
            config.headers = {}
        }
        config.headers['Authorization'] = `Bearer ${localStorage.getItem('TOKEN_INFO')}`
        return config
    }
)

export default api;
